package com.simple.simple_view.utils;

import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/*
 *@description: BeanCopyUtil
 *@author: hisen
 *@Time: 2023/10/29  10:09
 */
public class BeanCopyUtil {
    //私有构造表名此对象不能被new出来
    private BeanCopyUtil() {
    }

    ;

    public static <V> V copyBean(Object source, Class<V> clazz) {
        V result = null;
        try {
            //获取要封装对象字节码文件
            result = clazz.newInstance();
            //封装
            BeanUtils.copyProperties(source, result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //返回数据
        return result;
    }

    public static <T, V> List<V> copyBeanList(List<T> objects, Class<V> clazz) {
        //采用流操作
        return objects.stream()
                .map(o -> copyBean(o, clazz))
                .collect(Collectors.toList());

    }
    public static Map<String, Object> objectToMap(Object object) throws IllegalAccessException {
        Map<String,Object> dataMap = new HashMap<>();
        Class<?> clazz = object.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            dataMap.put(field.getName(),field.get(object));
        }
        return dataMap;
    }
}